<template>
  <el-drawer
    ref="drawerBox"
    :title="title"
    :visible.sync="dialogVisible"
    class="related-order-drawer"
    append-to-body
    size="80%"
    @closed="onDrawerClosed"
  >
    <div class="table-right-operate">
      <IconAmountLayout :amount="list.totalAmount / 100" :amount-text="amountText"/>
      <btnGroup
        ref="btnGroupRef"
        :list="[{
          label:'导出',
          exportApi,
          exportName: title,
          beforeExport: beforeExport,
          type: 'export'
        }]"
      />
    </div>
    <template v-if="dialogModel === REPORTS_MODEL.CHANNEL">
      <el-tabs
        slot="title"
        v-model="curActive"
        :before-leave="() => !listLoading"
        class="related-order-tabs"
        @tab-click="onOrderChange">
        <el-tab-pane name="0" label="按订单展示" />
        <el-tab-pane name="1" label="按销售展示" />
      </el-tabs>
      <div class="drawer-content">
        <filter-input
          ref="FilterToolRef"
          v-model="paramsObj"
          :filter-list="filterList"
          show-search-btn
          @handelClick="queryClick"
          @queryEmpty="queryEmpty"
          @filterTagStatus="filterTagStatus"
        />
        <div class="table-list">
          <!--按订单展示（渠道订单）-->
          <ChannelOrder
            v-if="curActive === '0'"
            ref="channelOrder"
            :list="list"
            :list-loading="listLoading"
            :is-selected-order="false"
            :table-height="setTableHeight"
            :show-un-write-off-amount="returnType === RETURN_TYPE.OVERDRAFT || returnType === RETURN_TYPE.PENDING"
            :show-complete-write-off-amount="returnType === RETURN_TYPE.ARRIVAL"
            select-callback
            @tableSort="tableSort"
            @onSelectChange="onSelectChange"
          />
          <!--按销售展示-->
          <SaleTable
            v-else
            ref="saleTableRef"
            :list="list"
            :list-loading="listLoading"
            :is-init="isInit"
            :table-height="setTableHeight"
            @tableSort="tableSort"
            @handleSelectionChange="handleSelectionChange"
          />
        </div>
      </div>
    </template>
    <div v-else class="drawer-content">
      <FilterInput
        ref="FilterToolRef"
        v-model="paramsObj"
        :filter-list="filterList"
        show-search-btn
        style="margin-bottom: 12px"
        @handelClick="queryClick"
        @queryEmpty="queryEmpty"
        @filterTagStatus="filterTagStatus"/>
      <!-- 财务流水 -->
      <DayAccountTable
        v-if="dialogModel === REPORTS_MODEL.FINANCE"
        ref="dayAccountTable"
        :list="list"
        :list-loading="listLoading"
        :is-init="isInit"
        :finance-list-setting="financeListSetting"
        :show-operate="false"
        :active-id="-1"
        :table-height="setTableHeight"
        open-new-page
        @addSort="tableSort"
        @handleSelectionChange="handleSelectionChange"
      />
      <!-- 核销记录 -->
      <ChargeReportTable
        v-else-if="dialogModel === REPORTS_MODEL.CHARGE_REPORT"
        ref="chargeReportTableRef"
        :list="list"
        :list-loading="listLoading"
        :is-init="isInit"
        :table-height="setTableHeight"
        @tableSort="tableSort"
        @handleSelectionChange="handleSelectionChange"
      />
    </div>
    <fixed-pagination v-show="list.total > 0">
      <div class="flex-center" style="flex: 1">
        <div v-if="selectedNums" class="select-box-style">
          <span class="select-data-num">已选 <span>{{ selectedNums }}</span> 条</span>
          <el-button type="text" @click="clearSelect"><span class="el-icon-close"/></el-button>
        </div>
      </div>
      <el-pagination
        :current-page="list.page"
        :page-size="list.perPage"
        :total="list.total"
        :page-sizes="[20, 50, 100]"
        :pager-count="5"
        layout="total, prev, pager, next, sizes, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </fixed-pagination>
  </el-drawer>
</template>

<script>
// component
import FilterInput from '@/components/Tool/filter';
import ChannelOrder from '@/components/legal/orderList/channelOrder';
import SaleTable from './module/saleTable';
import DayAccountTable from '@/components/Finance/DayAccountTable';
import { initFinanceList } from '@/components/OrderList/settingData';
import ChargeReportTable from './module/chargeReportTable';
import btnGroup from '@/components/Common/baseComponent/btnGroup';
import IconAmountLayout from '@/components/Common/IconAmountLayout';
// api
import { getList as getChannelOrders } from '@/api/order';
import { getReturnSaleList } from '@/api/customer';
import { getList as queryFinanceList, getChargeReports } from '@/api/finance';
// utils
import { verificationOptions } from '@/views/project/model/selectData';
import { paramsAryToStr, paramsRangeFormat } from '@/utils/paramsFormat';
import { EXPORT_API, REPORTS_MODEL, RETURN_TYPE } from '@/utils/const/returnedMoney';
import { showModal } from '@/utils/message';
// mixin
import paramsDateFormat from '@/mixins/paramsDateFormat';
import TableAdaptive from '@/mixins/tableAdaptive';
import drawerConfig from './mixins/drawerConfig';
export default {
  name: 'ReportsCommonDialog',
  components: {
    FilterInput,
    ChannelOrder,
    SaleTable,
    DayAccountTable,
    btnGroup,
    IconAmountLayout,
    ChargeReportTable
  },
  mixins: [paramsDateFormat, TableAdaptive, drawerConfig],
  props: {},
  data() {
    return {
      REPORTS_MODEL,
      RETURN_TYPE,
      initFinanceList,
      verificationOptions,
      curActive: '0',
      dialogModel: '0', // 弹窗模板类型
      title: '',
      amountText: '金额',
      paramsObj: {},
      page: 1,
      perPage: 20,
      returnType: '', // 明细类型
      typeField: '', // 表中单元格对应类型
      list: {
        items: [],
        page: 1,
        perPage: 20,
        total: 0,
        totalAmount: null
      },
      dialogVisible: false,
      listLoading: true,
      isInit: true,
      exportApi: '',
      exportName: '',
      selectData: {},
      mainId: '', // 传入用以筛选列表数据的id
      selectedIds: '', // 当前选中的列表id
      totalAmount: null,
      /**
       * 对应类型筛选项是否已请求
       * */
      initChannel: false,
      initFinance: false,
      initChargeReport: false
    };
  },
  computed: {
    tableOutsideHeight() {
      return 170;
    },
    selectedNums() {
      if (!this.selectedIds) return 0;
      return this.selectedIds.split(',').length;
    },
    filterList() {
      let filters = [];
      switch (this.dialogModel) {
        case REPORTS_MODEL.CHANNEL:
          if (this.curActive === '1') {
            filters = [
              { keyword: 'market', name: '销售', type: 'input' },
              { keyword: 'taxAmount', name: '含税金额', type: 'inputRange' },
              { keyword: 'writeOffAmount', name: '核销金额', type: 'inputRange' },
              { keyword: 'unWriteOffAmount', name: '待核销金额', type: 'inputRange' },
              // 下拉
              {
                keyword: 'departmentIds',
                name: '所属部门',
                type: 'cascaderSelectWithChild',
                childrenVal: 'children',
                options: this.deptTreeList
              }
            ];
          } else {
            filters = [
              { keyword: 'orderId', name: '订单编号', type: 'input' },
              { keyword: 'resourceName', name: '账号', type: 'input' },
              { keyword: 'theme', name: '品牌名称', type: 'input' },
              { keyword: 'orderOperator', name: '执行人', type: 'input' },
              { keyword: 'market', name: '销售', type: 'input' },
              { keyword: 'clientName', name: '客户名称', type: 'input' },
              { keyword: 'clientSettlementId', name: '客户结算单', type: 'input' },
              { keyword: 'taxAmount', name: '含税金额', type: 'inputRange' },
              { keyword: 'orderTime', name: '下单日期', timeType: 'daterange', type: 'rangeDate' },
              // 下拉
              { keyword: 'departmentId', name: '所属部门', type: 'cascaderSelect', childrenVal: 'children', strictly: true, options: this.deptTreeList },
              { keyword: 'orderPlatformId', name: '下单平台', type: 'select', options: this.orderPlatformOption }
            ];
          }
          break;
        case REPORTS_MODEL.FINANCE:
          filters = [
            { keyword: 'clientName', name: '付款人名称', type: 'input' },
            { keyword: 'payName', name: '付款账号', type: 'input' },
            { keyword: 'transactionNumber', name: '交易单号', type: 'input' },
            { keyword: 'flowNumber', name: '流水单号', type: 'input' },
            { keyword: 'createName', name: '创建人', type: 'input' },
            { keyword: 'remark', name: '备注', type: 'input' },
            { keyword: 'incomeAmount', name: '收入金额', type: 'inputRange' },
            { keyword: 'chargeAmount', name: '可核销金额', type: 'inputRange' },
            { keyword: 'verificationState', name: '核销状态', type: 'mulSelect', options: this.verificationOptions },
            { keyword: 'sealingState', name: '封账状态', type: 'select', options: this.sealingStateOption },
            { keyword: 'payType', name: '付款方式', type: 'select', options: this.payOption },
            { keyword: 'clientType', name: '付款人类型', type: 'select', options: this.clientTypeOption },
            { keyword: 'departmentId', name: '所属部门', type: 'select', options: this.departmentList, isSearch: true },
            { keyword: 'flowType', name: '类型', type: 'select', options: this.flowTypes },
            { keyword: 'createTime', name: '创建时间', type: 'rangeDate', timeType: 'daterange', format: 'yyyy/MM/dd' },
            { keyword: 'arrivalTime', name: '到账日期', type: 'rangeDate', timeType: 'daterange', format: 'yyyy/MM/dd' }
          ];
          break;
        case REPORTS_MODEL.CHARGE_REPORT:
          filters = [
            { keyword: 'verificationId', name: '核销编号', type: 'input', labelWidth: '100px' },
            { keyword: 'orderId', name: '订单编号', type: 'input' },
            { keyword: 'payer', name: '付款人名称', type: 'input', labelWidth: '100px' },
            { keyword: 'clientName', name: '客户名称', type: 'input' },
            { keyword: 'payAccount', name: '付款账号', type: 'input', labelWidth: '100px' },
            { keyword: 'trasactionId', name: '交易单号', type: 'input' },
            { keyword: 'flowId', name: '流水单号', type: 'input', labelWidth: '100px' },
            { keyword: 'flowCreater', name: '流水创建人', type: 'input' },
            { keyword: 'payMethod', name: '付款方式', type: 'select', options: this.payOption },
            { keyword: 'sealStatus', name: '封账状态', type: 'select', options: this.sealingStateOption },
            { keyword: 'flowType', name: '类型', type: 'select', labelWidth: '40px', options: this.flowTypes },
            { keyword: 'intoAccountTime', name: '到账日期', type: 'rangeDate', timeType: 'daterange', format: 'yyyy/MM/dd', labelWidth: '100px' },
            { keyword: 'chargeTime', name: '核销日期', type: 'rangeDate', timeType: 'daterange', format: 'yyyy/MM/dd' },
            { keyword: 'placeOrderTime', name: '下单日期', type: 'rangeDate', timeType: 'daterange', format: 'yyyy/MM/dd', labelWidth: '100px' },
            { keyword: 'sealingMonth', name: '封账月份', timeType: 'monthrange', type: 'rangeDate', format: 'yyyy/MM' },
            { keyword: 'sealMonth', name: '订单封账月份', timeType: 'monthrange', type: 'rangeDate', format: 'yyyy/MM', labelWidth: '100px' },
            {
              keyword: 'charger',
              name: '核销人员',
              type: 'loadMoreSelect',
              valueName: 'id',
              multiple: true,
              labelName: 'userName',
              placeholder: '核销人员',
              searchkeyword: 'userName',
              apiUrl: '/admin/user/list'
            }
          ];
          break;
      }
      return filters;
    }
  },
  methods: {
    init(id, returnType, typeField) {
      if (returnType == null) {
        this.$message.warning('未知弹窗类型');
        return;
      } else if (id == null || typeField == null) {
        this.$message.warning('暂无数据');
        return;
      }
      this.returnType = returnType;
      this.typeField = typeField;
      this.setDrawerType(returnType);
      this.mainId = id;
      switch (this.dialogModel) {
        case REPORTS_MODEL.CHANNEL:
          if (!this.initChannel) {
            this.queryDeptTreeList();
            this.platformList();
            this.initChannel = true;
          }
          break;
        case REPORTS_MODEL.FINANCE:
          if (!this.initFinance) {
            this.getSettingData();
            this.getPaySelect();
            this.getDepartment();
            this.initFinance = true;
          }
          break;
        case REPORTS_MODEL.CHARGE_REPORT:
          if (!this.initChargeReport) {
            this.getPaySelect();
            this.initChargeReport = true;
          }
          break;
      }
      this.$nextTick(() => {
        this.$refs['FilterToolRef'].changeSelectKey();
      });
      this.clearMixinSelection();
      this.fetchData(true);
      this.dialogVisible = true;
    },
    // 格式化各个列表的入参
    formatParams() {
      const params = _.cloneDeep(this.paramsObj);
      switch (this.dialogModel) {
        case REPORTS_MODEL.CHANNEL:
          if (this.curActive === '0') {
            paramsRangeFormat(this.channelRangeKeys, params);
            params.excludeFinalOrder = true; // 排除最终单
          } else {
            paramsRangeFormat(this.saleRangeKeys, params);
            paramsAryToStr(['departmentIds'], params);
          }
          break;
        case REPORTS_MODEL.FINANCE:
          paramsRangeFormat(this.financeRangeKeys, params);
          this.paramsDateFormat(this.dateDataAttrName, params, 1);
          params.verificationState && (params.verificationState = params.verificationState.join());
          break;
        case REPORTS_MODEL.CHARGE_REPORT:
          this.paramsDateFormat(this.chargeReportDateNames, params);
          if (params.charger && params.charger.length > 0) {
            params.charger = params.charger.join(',');
          }
          break;
      }
      params.returnId = this.mainId;
      params.returnType = this.returnType;
      params.typeField = this.typeField;
      params.excludeAuth = true;
      params.sortName = this.sortName || '';
      params.sortType = this.sortType || '';
      params.page = this.page;
      params.perPage = this.perPage;
      return params;
    },
    // 获取列表数据
    fetchData(reset = false) {
      reset && (this.page = 1);
      const params = this.formatParams();
      this.listLoading = true;
      switch (this.dialogModel) {
        case REPORTS_MODEL.CHANNEL:
          if (this.curActive === '1') {
            this.queryReturnSaleList(params);
          } else {
            this.queryChannelOrders(params);
          }
          break;
        case REPORTS_MODEL.FINANCE:
          this.queryFinanceOrders(params);
          break;
        case REPORTS_MODEL.CHARGE_REPORT:
          this.queryChargeReports(params);
          break;
      }
    },
    clearSelect() {
      showModal('是否清空已勾选的数据？', '').then(() => {
        this.selectedIds = '';
        this.clearMixinSelection();
      });
    },
    resetData() {
      this.paramsObj = {};
      this.sortName = '';
      this.sortType = '';
      this.selectedIds = '';
      this.list.items = [];
      this.list.total = 0;
      this.isInit = true;
      this.list.totalAmount = null;
    },
    // 切换订单tab
    onOrderChange() {
      this.resetData();
      this.clearMixinSelection();
      this.$refs['btnGroupRef'].loading = false;
      this.exportApi = this.curActive === '0' ? EXPORT_API.ORDER : EXPORT_API.SALE;
      this.fetchData(true);
      this.$nextTick(() => {
        this.$refs['FilterToolRef'].changeSelectKey();
      });
    },
    // 渠道单列表
    queryChannelOrders(params) {
      getChannelOrders(this.page, this.perPage, params).then(res => {
        res.data && res.data.items.map(item => { // 添加订单类型的icon,颜色
          const typeImg = this.orderTypeImg.find(currentValue => item.orderType === currentValue.type);
          const reviewState = this.reviewState.find(currentValue => item.reviewState === currentValue.status);
          if (item.orderInfo.orderKind && item.orderInfo.orderKind.length) item.orderInfo.orderKindName = item.orderInfo.orderKind.map(i => i.orderKindName).join('，');
          item = Object.assign(item, typeImg, reviewState);
          return item;
        });
        this.list = res.data;
        this.totalAmount = res.data.totalAmount;
        this.listLoading = false;
      }).catch(_ => {
        this.listLoading = false;
      });
    },
    // 按销售类型
    queryReturnSaleList(params) {
      getReturnSaleList(params).then(({ data }) => {
        this.list = data;
        this.isInit = false;
        this.totalAmount = data.totalAmount;
        this.listLoading = false;
      }).catch(_ => {
        this.listLoading = false;
        this.isInit = false;
      });
    },
    // 财务流水列表
    queryFinanceOrders(params) {
      queryFinanceList(this.page, this.perPage, params).then(({ data }) => {
        this.isInit = false;
        data.items.map(item => { // 添加订单类型的icon,颜色
          const verificationStateObj = this.verificationState.find(currentValue => item.verificationState === currentValue.status);
          item = Object.assign(item, verificationStateObj);
          return item;
        });
        this.list = data;
        this.totalAmount = data.totalAmount;
        this.listLoading = false;
      }).catch(_ => {
        this.isInit = false;
        this.listLoading = false;
      });
    },
    // 核销记录列表
    queryChargeReports(params) {
      getChargeReports(this.page, this.perPage, params).then(res => {
        if (res.code === 200) {
          this.list = res.data;
          this.totalAmount = res.data && res.data.totalAmount;
        }
        this.isInit = false;
        this.listLoading = false;
      }).catch(_ => {
        this.isInit = false;
        this.listLoading = false;
      });
    },
    // 列表导出
    beforeExport() {
      const params = this.formatParams();
      params.ids = this.selectedIds;
      this.$refs['btnGroupRef'] && this.$refs['btnGroupRef'].btnExport(params);
    },
    clearMixinSelection() {
      this.$refs['channelOrder'] && this.$refs['channelOrder'].clearMixinSelection();
      this.$refs['saleTableRef'] && this.$refs['saleTableRef'].clearMixinSelection();
      this.$refs['dayAccountTable'] && this.$refs['dayAccountTable'].clearMixinSelection();
      this.$refs['chargeReportTableRef'] && this.$refs['chargeReportTableRef'].clearMixinSelection();
    },
    tableSort(obj) {
      this.sortName = obj.sortName;
      this.sortType = obj.sortType;
      this.fetchData(true);
    },
    queryClick() {
      this.fetchData(true);
    },
    queryEmpty() {
      this.clearMixinSelection();
      this.resetData();
      this.fetchData(true);
    },
    // 保存选中的订单数据
    onSelectChange(name, data) {
      this.setSelectedIds(data);
    },
    handleSelectionChange(e) {
      const data = _.cloneDeep(e);
      this.setSelectedIds(data);
    },
    setSelectedIds(data) {
      if (Array.isArray(data) && data.length) {
        this.selectedIds = data.map(item => item.id).join();
      } else {
        this.selectedIds = '';
      }
    },
    handleSizeChange(val) {
      this.perPage = val;
      this.fetchData(true);
      this.$nextTick(() => {
        document.body.scrollTop = document.documentElement.scrollTop = 0;
      });
    },
    handleCurrentChange(toPage) {
      this.page = toPage;
      this.fetchData();
      this.$nextTick(() => {
        document.body.scrollTop = document.documentElement.scrollTop = 0;
      });
    },
    onDrawerClosed() {
      this.resetData();
      this.curActive = '0';
      this.$refs['btnGroupRef'].loading = false;
      this.dialogVisible = false;
    }
  }
};
</script>

<style scoped lang="scss">
.related-order-drawer {
  &::v-deep {
    .el-drawer {
      min-width: 300px;
    }
    .el-badge__content {
      display: flex;
      align-items: center;
    }
    .el-tabs__header {
      border-bottom: none;
    }
    .pagination-flex {
      position: absolute;
      width: 100% !important;
    }
    .el-tabs__nav-wrap::after {
      z-index: -1;
    }
    .el-tabs__active-bar {
      bottom: 1px;
    }
    .el-drawer__header {
      height: 48px;
      padding: 0 12px 0 24px;
      margin: 0;
      box-shadow: 2px 4px 5px 0 rgba(221,225,234,0.3);
      display: flex;
      align-items: center;
      overflow-x: auto;
      > span {
        font-size: 14px;
        color: #333;
      }
      .el-tabs__nav-wrap::after {
        height: 0 !important;
      }
    }
    .el-tabs__header {
      margin: 0;
    }
    .el-drawer__body {
      overflow-y: auto;
      margin-bottom: 56px;
    }
    .related-order-tabs {
      .el-tabs__header {
        .el-tabs__active-bar {
          display: none;
        }
        .el-tabs__nav-wrap::after {
          display: none;
        }
      }
      .el-tabs__item {
        font-size: 16px;
      }
      .is-active {
        font-weight: bold;
      }
    }
  }
  .table-right-operate {
    display: flex;
    position: absolute;
    right: 24px;
    top: 70px;
  }
  .drawer-content {
    padding: 22px 24px 0;
    overflow-y: auto;
    .table-list {
      border-radius: 10px;
      margin-top: 12px;
      .el-row {
        padding: 0;
      }
    }
  }
}
</style>
